package de.baumann.browser.activitys.card

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.Toast
import de.baumann.browser.BuildConfig
import de.baumann.browser.R
import de.baumann.browser.adapter.CardPowerAdapter
import de.baumann.browser.adapter.PowerDescAdapter
import de.baumann.browser.api.net.vo.Card
import de.baumann.browser.api.net.vo.PowerDesc
import de.baumann.browser.base.BaseOdinActivity
import de.baumann.browser.iview.ICardDetailView
import de.baumann.browser.present.CardDetailPresenter
import de.baumann.browser.utils.getUser
import de.baumann.browser.utils.web3j.WalletDaoUtils
import de.baumann.browser.views.dialog.BuyCardDialog
import de.baumann.browser.views.dialog.PayPwdDialog
import kotlinx.android.synthetic.main.activity_card_detail.*
import kotlinx.android.synthetic.main.include_tool_bar.*
import org.web3j.crypto.WalletUtils
import java.io.File

class CardDetailActivity : BaseOdinActivity<ICardDetailView, CardDetailPresenter>(), ICardDetailView {

    companion object {
        fun startCardDetailActivity(context: Activity, card: Card, requestCode: Int) {
            context.startActivityForResult(Intent(context, CardDetailActivity::class.java)
                    .apply {
                        putExtra("card", card)
                    }
                    , requestCode)
        }
    }

    private var powerTextColor = R.color.color_999999

    override fun getLayout(): Int {
        return R.layout.activity_card_detail
    }

    private lateinit var buyCardDialog: BuyCardDialog
   private var pwdd: PayPwdDialog? = null
    override fun initView() {
        initToolbar(commToolBar, null)

        rvDtlCardPower.layoutManager = LinearLayoutManager(mContext)
        rvDtlDesc.layoutManager = LinearLayoutManager(mContext)

        btnDetailBuy.setOnClickListener {
            if (getCard().buyFlag == 0) {
                showShortToast(getCard().buyMsg)
                return@setOnClickListener
            }
            var address = getUser()?.eth_address
            if (address == null) {
                showShortToast("地址获取失败，请重新登录")
                return@setOnClickListener
            }
            if (address.startsWith("odx")) {
                address = "0${address.substring(2)}"
            }

            val ethWallet = WalletDaoUtils.queryWalletByAddress(address)

            if (ethWallet == null) {
                showShortToast("请导入绑定地址对应的钱包")
                return@setOnClickListener
            }

            buyCardDialog = BuyCardDialog(mContext, getCard().cardName, getCard().cardPrice, View.OnClickListener {
                buyCardDialog.dismiss()
                pwdd = PayPwdDialog(mContext, object : PayPwdDialog.PwdCallback {
                    override fun callback(pwd: String) {
                        try {
                            val credentials = WalletUtils.loadCredentials(pwd, File(ethWallet.keystorePath))
                            val privateKey = credentials.ecKeyPair.privateKey
                            presenter.transfer(credentials.address, privateKey.toString(16))
                            pwdd!!.dismiss()
                        } catch (e: Exception) {
                            if ("Invalid password provided" == e.message) {
                                Toast.makeText(mContext, "密码错误", Toast.LENGTH_SHORT).show()
                            } else {
                                Toast.makeText(mContext, e.message, Toast.LENGTH_SHORT).show()
                            }
                        }
                    }
                })

                pwdd!!.show()
            })
            buyCardDialog.show()
        }
    }

    override fun initData() {
        presenter.getCardData()
    }

    override fun createPresenter(): CardDetailPresenter {
        return CardDetailPresenter()
    }

    override fun createView(): ICardDetailView {
        return this
    }

    override fun getCard(): Card {
        return intent.getSerializableExtra("card") as Card
    }

    @SuppressLint("SetTextI18n")
    override fun setCardName(cardName: String) {
        dtlCardName.text = cardName
        commTitle.text = cardName
        activePlanDetail.text = cardName + "活动详情"
    }

    override fun setCardPrice(price: String) {
        dtlCardPrice.text = price
    }

    override fun setCardType(type: Int) {
        var cardBg = R.drawable.blackcard_bg_black
        var cardTextColor = R.color.windowLight


        when (type) {
            0 -> {
                cardBg = R.drawable.blackcard_bg_black
                cardTextColor = R.color.windowLight
                powerTextColor = R.color.color_999999
            }
            1 -> {
                cardBg = R.drawable.blackcard_bg_gold
                cardTextColor = R.color.color_black_121212
                powerTextColor = R.color.color_666666
            }
            2 -> {
                cardBg = R.drawable.blackcard_bg_white
                cardTextColor = R.color.color_black_121212
                powerTextColor = R.color.color_666666
            }
        }
        rlCard.setBackgroundResource(cardBg)
        dtlCardName.setTextColor(resources.getColor(cardTextColor))
        dtlCardEndTime.setTextColor(resources.getColor(cardTextColor))
        dtlCardPrice.setTextColor(resources.getColor(cardTextColor))
    }

    override fun setCardPower(powers: List<String>) {
        rvDtlCardPower.adapter = CardPowerAdapter(mContext, powers, powerTextColor)
    }

    override fun setCardPowerDescs(powerDescs: List<PowerDesc>) {
        rvDtlDesc.adapter = PowerDescAdapter(powerDescs)
    }


    override fun getToAddress(): String {
        return BuildConfig.BUY_CARD_ADDRESS
    }

    override fun getAmount(): String {
        return getCard().cardPrice
    }

    override fun getLimit(): Long {
        return 80000L
    }

    override fun transferSuccess(hash: String) {
        presenter.callAfterBuy(getCard().cardId.toString(), hash)
    }

    override fun buySuccess() {
        showShortToast("请求已提交，请等待处理")
        setResult(Activity.RESULT_OK)
        finish()
    }
}
